package org.jeecg.modules.meter.iot.command;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.modules.system.util.RestTemplateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;


/**
 * 裕沛仪表对接处理
 * @Author liurui
 * @Date 2020-12-03 22:56
 * @Version 1.0
 **/
@Slf4j
@Component
public class MeterYuPeiCommand implements IotCommand {

    private final static String SUCCESS = "0";  //成功
    @Autowired
    private RestTemplateUtil restTemplateUtil;


    @Override
    public boolean serviceInvoke(String jsonParam, String productKey, String requestUrl,String requestMethod) throws Exception {
        requestUrl = requestUrl + "/" + requestMethod;
        JSONObject json =  restTemplateUtil.postForEntityJson(jsonParam,requestUrl,null);
//        boolean success = json.getBooleanValue("success");
        if (json != null){
            String code = json.getString("code");
            if (null != code && code.equals(SUCCESS)){
                return true;
            }else {
                return false;
            }
        }
        return false;
    }

    @Override
    public String serviceInvokeWithData(String jsonParam, String productKey, String requestUrl,String requestMethod) throws Exception {
        requestUrl = requestUrl + "/" + requestMethod;
        JSONObject json =  restTemplateUtil.postForEntityJson(jsonParam,requestUrl,null);
//        boolean success = json.getBooleanValue("success");
        if (json != null){
            String code = json.getString("code");
            if (null != code && code.equals(SUCCESS)){
                String data = json.getString("data");
                return data;
            }
        }
        return null;
    }

    @Override
    public JSONArray serviceInvokeWithArrayData(String jsonParam, String productKey, String requestUrl,String requestMethod) throws Exception {
        requestUrl = requestUrl + "/" + requestMethod;
        JSONObject json =  restTemplateUtil.postForEntityJson(jsonParam,requestUrl,null);
//        boolean success = json.getBooleanValue("success");
        log.info("电表硬件读取数据:{}",json);
        if (json != null){
            String code = json.getString("code");
            if (null != code && code.equals(SUCCESS)){
                JSONArray array = json.getJSONArray("data");
                return array;
            }
        }
        return null;
    }
}
